import * as dd from 'dingtalk-jsapi';
import services from '../api/mine';
import config from '../config';
import axios from 'axios';
import {
  getURLParameter
} from '../utils';
import info from './mine/user';
import Toast from './../components/toast';

import {
  ddlwp
} from "./ddlwp"

const getCode = () => {
  return services.getJsConfig().then((res) => {
    const jsConfig = res.result;
    dd.config({
      ...jsConfig,
      jsApiList: [
        'biz.util.uploadImageFromCamera',
        "biz.clipboardData.setData",
        "biz.util.setScreenBrightnessAndKeepOn"
      ],
      onFail: (err) => console.log(err)
    });


    return new Promise((resolve, reject) => {
      dd.ready(function () {
        dd.runtime.permission.requestAuthCode({
          corpId: jsConfig.corpId,
          onSuccess: ({
            code
          }) => {
            config.dingtalk.code = code;
            resolve(code);
          },
          onFail: function (err) {
            console.log(err);
            reject(err);
          }
        });
      });
    });
  });
};

const setConfig = async () => {
  const appkey = getURLParameter('appkey');
  const corpId = getURLParameter('corpId');

  if (appkey) config.dingtalk.appKey = appkey;
  if (corpId) config.dingtalk.corpId = corpId;

  config.dingtalk.code = await getCode(config.dingtalk.corpId);
  return config.dingtalk;
}

function ddlwpWay() {
  return new Promise((resolve) => {
    ddlwp(sessionStorage.getItem("corpId")).then(res => {
      console.log('ddlwp', res);
      axios.defaults.headers.common['Authorization'] = res.result.token; //请求头文件
      if (res.success) {
        if (res.result && res.result.user && res.result.user.userid) {
          sessionStorage.setItem("zhuansong", res.result.user.userid);
        }
        console.log('zhuansong', sessionStorage.getItem("zhuansong"));
        resolve(true);
      } else {
        Toast(res.errorMsg || '用户信息获取失败');
        resolve(false);
      }

    }, err => {
      Toast(err);
      resolve(false);
    });
  });
}

export default async (to, next) => {
  const {
    dingtalk = false
  } = to.meta;

  if (!dingtalk) return false;

  const way = '2'; //1之前 2ddlwp
  if (way == '1') {
    const {
      appKey,
      corpId,
      code
    } = await setConfig();


    const
      res = await services.login({
        appkey: appKey,
        corpId,
        code
      });
    Object.assign(info, res.result.user);
    sessionStorage.setItem("zhuansong", res.result.user.userid);
    config.dingtalk.token = res.result.token;
    axios.defaults.headers.common['Authorization'] = res.result.token; //请求头文件

    next();

    return true;
  } else {
    // 改成lwp方式不要签名，有此方式免登
    sessionStorage.setItem("corpId", decodeURIComponent((new RegExp('[?|&]' + 'corpId' + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || '');
    let resDdlwpWay = await ddlwpWay();
    return !resDdlwpWay; //返回值未true  则会return 不显示页面
  }


};
